<template>
  <div class="detailWrapBoxCe">
    <div @click="clearDetailIndex" class="topBack"><i></i></div>
    <div class="detailBody">
      <div class="leftBox">
        <div class="chart-container" ref="chartRef"></div>
      </div>
      <div class="rightBox">
        <div class="airport-container">
          <div
            class="tableParts"
            v-for="item in currentAirport"
            :key="item.identifier"
          >
            <div class="tableTitle">
              <i></i><span>{{ item.city }}/{{ item.name }}</span>
            </div>
            <div class="tableTH">
              <div class="box1">起始时间（UTC）</div>
              <div class="box1">结束时间（UTC）</div>
              <div class="box2">状态</div>
              <div class="box1">持续时间</div>
            </div>
            <div
              class="tableTR"
              v-for="(itemChild, index) in item.rawResults"
              :key="index"
            >
              <div class="box1" v-if="itemChild.isAvailable == 1">
                {{ itemChild.startTime }}
              </div>
              <div
                class="box1"
                style="color: #ff0004"
                v-if="itemChild.isAvailable == 0"
              >
                {{ itemChild.startTime }}
              </div>
              <div class="box1" v-if="itemChild.isAvailable == 1">
                {{ itemChild.endTime }}
              </div>
              <div
                class="box1"
                style="color: #ff0004"
                v-if="itemChild.isAvailable == 0"
              >
                {{ itemChild.endTime }}
              </div>
              <div
                class="box2"
                style="color: #3aff7f"
                v-if="itemChild.isAvailable == 1"
              >
                可用
              </div>
              <div
                class="box2"
                style="color: #ff0004"
                v-if="itemChild.isAvailable == 0"
              >
                不可用
              </div>
              <div class="box1" v-if="itemChild.isAvailable == 1">
                {{ itemChild.timeString }}
              </div>
              <div
                class="box1"
                style="color: #ff0004"
                v-if="itemChild.isAvailable == 0"
              >
                {{ itemChild.timeString }}
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import {
  ref,
  onMounted,
  onUnmounted,
  watchEffect,
  defineProps,
  defineEmits,
  computed,
} from "vue";
import * as echarts from "echarts";

// 接收父组件传递的机场数据
const props = defineProps({
  airTestsObj: {
    type: Object,
    default: () => ({}),
  },
});

const emit = defineEmits(["update-curr-detail-index"]);

// 右侧表格数据
const currentAirport = computed(() => {
  return Object.values(props.airTestsObj.airportResults || {}).map(
    (airportItem) => {
      return {
        identifier: airportItem.identifier,
        city: airportItem.city,
        startTime: airportItem.startTime,
        endTime: airportItem.endTime,
        name: airportItem.name,
        rawResults: airportItem.rawResults,
      };
    }
  );
});

const chartRef = ref(null);
let myChart = null;

// 标准化X轴标签数据
const xAxisLabelData = computed(() => {
  return Object.values(props.airTestsObj.airportResults || {}).map(
    (airport) => ({
      left: airport.city || "",
      right: airport.name || "",
    })
  );
});

// 去重处理
const uniqueXAxisLabelData = computed(() => {
  const seen = new Set();
  return xAxisLabelData.value.filter((item) => {
    const key = `${item.left}/${item.right}`;
    if (!seen.has(key)) {
      seen.add(key);
      return true;
    }
    return false;
  });
});
// 表的Y轴数据
const rawData = computed(() => {
  const airportValues = Object.values(props.airTestsObj.airportResults);
  const maxRawResultsLength = Math.max(
    ...airportValues.map((airport) => airport.rawResults.length)
  );
  // 创建结果二维数组
  const result = [];
  for (let i = 0; i < maxRawResultsLength; i++) {
    const row = [];
    airportValues.forEach((airport) => {
      const minuteValue = airport.rawResults[i]?.minutes || 0;
      row.push(minuteValue);
    });
    result.push(row);
  }
  console.log(result, "rawData-result");
  return result;
});

const crossDayTotalHours = 4320;

const statusData = computed(() => {
  const airportValues = Object.values(props.airTestsObj.airportResults);
  const maxRawResultsLength = Math.max(
    ...airportValues.map((airport) => airport.rawResults.length)
  );
  // 创建结果二维数组
  const result = [];
  for (let i = 0; i < maxRawResultsLength; i++) {
    const row = [];
    airportValues.forEach((airport) => {
      const statusValue =
        airport.rawResults[i]?.isAvailable == 0 ? "不可用" : "可用";
      row.push(statusValue);
    });
    result.push(row);
  }
  console.log(result, "---");
  return result;
});

// const statusData = ref([
//   ["可用", "可用", "可用", "可用", "可用"],
//   ["不可用", "", "", "", ""],
//   ["可用", "", "", "", ""],
// ]);

const statusColors = {
  可用: "#7eed8d",
  不可用: "#ed5652",
};

// 数据平衡方法
const balanceDailyData = () => {
  uniqueXAxisLabelData.value.forEach((_, dayIndex) => {
    const currentSum = rawData.value.reduce(
      (sum, category) => sum + category[dayIndex],
      0
    );
    if (Math.abs(currentSum - crossDayTotalHours) > 0.01) {
      rawData.value[rawData.value.length - 1][dayIndex] +=
        crossDayTotalHours - currentSum;
    }
  });
};

// 构建柱状图系列
const buildSeries = () => {
  return rawData.value.map((data, seriesIndex) => ({
    name: `系列${seriesIndex + 1}`,
    type: "bar",
    stack: "total",
    barWidth: "15%",
    label: {
      show: false,
    },
    data: data.map((value, dataIndex) => ({
      value,
      itemStyle: {
        color: statusColors[statusData.value[seriesIndex][dataIndex]],
      },
    })),
  }));
};

// 构建图表配置 - 修复了自定义系列的图形类型错误
const buildChartOption = () => {
  // 文本配置常量
  const TEXT_SIZE = 12;
  const CHAR_SPACING = 14;
  const COLUMN_GAP = 14;
  const LABEL_OFFSET_Y = 560;

  return {
    grid: {
      left: "5%",
      right: "5%",
      top: "2%",
      bottom: "15%",
      containLabel: true,
    },
    xAxis: {
      type: "category",
      data: uniqueXAxisLabelData.value.map((_, i) => i),
      axisLabel: { show: false },
      axisTick: { show: false },
      axisLine: { show: false },
      splitLine: { show: false },
    },
    yAxis: {
      type: "value",
      min: 0,
      max: crossDayTotalHours,
      interval: 720,
      axisLabel: {
        formatter: (value) => {
          const startDate = new Date(
            props.airTestsObj.forecastStartTime.replace(/-/g, "/")
          );
          const currentDate = new Date(startDate.getTime() + value * 60 * 1000);
          const month = String(currentDate.getMonth() + 1).padStart(2, "0");
          const day = String(currentDate.getDate()).padStart(2, "0");
          const hours = String(currentDate.getHours()).padStart(2, "0");
          const minutes = String(currentDate.getMinutes()).padStart(2, "0");
          return [
            `{line1|${month}-${day}}`,
            `{line2|${hours}:${minutes}}`,
          ].join("\n");
        },
        fontSize: 12,
        color: "#fff",
        align: "right",
        padding: [0, 10, 0, 0],
        rich: {
          line1: { lineHeight: 14 },
          line2: { lineHeight: 14 },
        },
      },
      axisLine: {
        show: true,
        lineStyle: {
          color: "#545f72",
          width: 1,
        },
      },
      splitLine: {
        show: false,
      },
    },
    series: [
      // 修复的自定义系列：将文本元素包装在group中
      {
        type: "custom",
        coordinateSystem: "cartesian2d",
        renderItem: (params, api) => {
          const x = api.coord([params.dataIndex, 0])[0];
          const { left, right } = uniqueXAxisLabelData.value[params.dataIndex];

          // 左列文本
          const leftChars = left.split("").map((char, i) => ({
            type: "text",
            position: [x - COLUMN_GAP / 2, i * CHAR_SPACING + LABEL_OFFSET_Y],
            style: {
              text: char,
              fontSize: TEXT_SIZE,
              fill: "#fff",
              textAlign: "center",
            },
          }));

          // 右列文本
          const rightChars = right.split("").map((char, i) => ({
            type: "text",
            position: [x + COLUMN_GAP / 2, i * CHAR_SPACING + LABEL_OFFSET_Y],
            style: {
              text: char,
              fontSize: TEXT_SIZE,
              fill: "#fff",
              textAlign: "center",
            },
          }));

          // 关键修复：将所有文本元素包装在一个group中
          return {
            type: "group",
            children: [...leftChars, ...rightChars],
          };
        },
        data: uniqueXAxisLabelData.value.map((_, i) => i),
      },
      // 原有柱状图系列
      ...buildSeries(),
    ],
    animation: true,
    animationDuration: 1000,
    animationEasing: "cubicOut",
  };
};

// 初始化图表
const initChart = () => {
  if (!chartRef.value || myChart) return;
  myChart = echarts.init(chartRef.value);
  balanceDailyData();
  myChart.setOption(buildChartOption());
};

const destroyChart = () => {
  if (myChart) {
    myChart.dispose();
    myChart = null;
  }
};

const clearDetailIndex = () => {
  emit("update-curr-detail-index", "");
};

onMounted(() => {
  initChart();
});

onUnmounted(() => {
  destroyChart();
});

watchEffect(() => {
  if (myChart) {
    balanceDailyData();
    myChart.setOption(buildChartOption());
  }
});
</script>

<style scoped lang="scss">
/* 样式保持不变 */
.detailWrapBoxCe {
  width: 100%;
  // height: 675px;
  height: calc(100% - 10px);
  overflow-y: auto;
  position: absolute;
  top: 0;
  left: 0;
  background: #070f24;
  z-index: 1;
  .topBack {
    cursor: pointer;
    width: 100%;
    height: 24px;
    i {
      float: left;
      width: 24px;
      height: 24px;
      background-image: url("../../../assets/images/raim/back.png");
      background-repeat: no-repeat;
      background-size: contain;
      background-position: center;
    }
  }
  .detailBody {
    width: 100%;
    overflow: hidden;
    .leftBox {
      float: left;
      width: 300px;
      padding: 20px 0;
      height: 650px;
      .chart-container {
        width: 100%;
        height: 650px;
        margin: 0 auto;
      }
    }
    .rightBox {
      padding-top: 20px;
      float: right;
      width: 580px;
      height: 630px;
      .tableParts {
        margin-bottom: 16px;
        overflow: hidden;
        .tableTitle {
          height: 24px;
          line-height: 24px;
          margin-bottom: 4px;
          i {
            float: left;
            width: 24px;
            height: 24px;
            background-image: url("../../../assets/images/raim/dingwei.png");
            background-repeat: no-repeat;
            background-size: contain;
            background-position: center;
          }
          span {
            float: left;
            color: #fff;
          }
        }
        .tableTH {
          overflow: hidden;
          height: 40px;
          line-height: 40px;
          font-size: 14px;
          font-weight: 700;
          background: rgba(0, 175, 255, 0.2);
          color: #c5d6e6;
          .box1 {
            float: left;
            width: 166px;
            text-align: left;
            text-indent: 16px;
          }
          .box2 {
            float: left;
            width: 70px;
            text-align: left;
            text-indent: 16px;
          }
        }
        .tableTR {
          overflow: hidden;
          height: 40px;
          line-height: 40px;
          font-size: 14px;
          color: #c5d6e6;
          &:nth-child(even) {
            background: rgba(0, 59, 122, 0.2);
          }
          .box1 {
            float: left;
            width: 166px;
            text-align: left;
            text-indent: 16px;
          }
          .box2 {
            float: left;
            width: 70px;
            text-align: left;
            text-indent: 16px;
          }
        }
      }
    }
  }
}
.airport-container {
  height: 586px;
  overflow-y: auto;
}

.airport-container::-webkit-scrollbar {
  width: 2px;
}
.airport-container::-webkit-scrollbar-track {
  background: rgba(6, 15, 37, 0.5);
  border-radius: 2px;
}

.airport-container::-webkit-scrollbar-thumb {
  background: rgba(0, 175, 255, 0.4);
  border-radius: 2px;
}

.airport-container::-webkit-scrollbar-thumb:hover {
  background: rgba(0, 175, 255, 0.6);
}

.airport-container {
  scrollbar-width: thin;
  scrollbar-color: rgba(0, 175, 255, 0.4) rgba(6, 15, 37, 0.5);
}
</style>
